import router from "@/router/index";
import { useUserStore } from "@/stores/modules/user";
import { useMenuStore } from "@/stores/modules/menu";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import Err404 from "@/components/Err404.vue";
import { deepCopy } from "@/utils";
import { getToken } from "@/utils/auth"; // 引入 getToken 方法

NProgress.configure({ showSpinner: false });
// 白名单路径
const whiteList = ['/login'];

router.beforeEach(async (to, from, next) => {
    console.log('router.beforeEach triggered'); // 添加日志
    console.log("路由拦截器");
    NProgress.start();
    const token = getToken(); // 获取 token
    // 白名单路径
    const whiteList = ['/login'];

    // 如果已经在登录页面,直接放行
    if (whiteList.includes(to.path)) {
        next();
        NProgress.done();
        return;
    }

    // 已登录状态处理
    if (token) {
        const userStore = useUserStore(); // 在路由守卫内部调用
        if (Object.keys(userStore.userInfo).length === 0) {
            try {
                // 获取用户基本信息
                await useUserStore._getUserInfo();
                // 动态添加路由
                const addRoutes = await filterAsyncRouter(useUserStore.menu);
                addRoutes.forEach(route => router.addRoute(route));

                // 添加404路由
                router.addRoute({
                    path: "*",
                    name: "err404",
                    meta: { title: "404" },
                    component: Err404,
                });

                next({ ...to, replace: true });
            } catch (error) {
                console.error('获取用户信息失败:', error);
                next('/login');
                return;
            }
        } else {
            next();
        }
        NProgress.done();
    } else {
        // 未登录,重定向到登录页面
        next('/login');
        NProgress.done();
    }
});

// convert routes component
async function filterAsyncRouter(asyncRouterMap) {
    const accessedRouters = [];
    for (const route of asyncRouterMap) {
        if (route.component) {
            try {
                // 使用动态 import 加载组件
                const component = await import(`@/views/${route.component}.vue`);
                route.component = component.default;
                if (route.children && route.children.length) {
                    route.children = await filterAsyncRouter(route.children);
                }
                accessedRouters.push(route);
            } catch (error) {
                console.error("路由组件加载失败:", error);
            }
        }
    }
    return accessedRouters;
}

router.afterEach(async (to, from) => {
    NProgress.done();
    document.title = to.meta.title ? `${to.meta.title} - 诺今生报名系统` : "诺今生报名系统";
    const menuStore = useMenuStore(); // 在路由守卫内部调用
    if (menuStore.menu.length) {
        if (to.path === "/") {
            let finallySubmenu = deepCopy(menuStore.menu[0]);
            router.push({
                path: finallySubmenu.children[0].path,
            });
            return;
        }
        for (let i = 0; i < menuStore.menu.length; i++) { // 这里也可能会出错
            for (let j = 0; j < menuStore.menu[i].children.length; j++) { // 这里同样可能出错
                const route = menuStore.menu[i].children[j];
                if (to.path === route.path) {
                    if (menuStore.currentMenuIndex === `${i}-${j}`) {
                        break;
                    } else {
                        menuStore.clickMenu(`${i}-${j}`);
                        break;
                    }
                }
            }
        }
    }
});
